package com.example.mscluster.provider.order;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.bind.ObjectTypeAdapter;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * JSON转换工具
 *
 * @author sucz
 * @create 2019/12/11 10:27
 */
public class GsonUtils {

    private static final Gson GSON;

    static {
        GSON = getGson();
    }

    @SuppressWarnings("unchecked")
    private static Gson getGson() {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        try {
            Field factories = Gson.class.getDeclaredField("factories");
            factories.setAccessible(true);
            Object obj = factories.get(gson);
            Class<?>[] classes = Collections.class.getDeclaredClasses();
            for (Class clazz : classes) {
                if ("java.util.Collections$UnmodifiableList".equals(clazz.getName())) {
                    Field field = clazz.getDeclaredField("list");
                    field.setAccessible(true);
                    List<TypeAdapterFactory> list = (List<TypeAdapterFactory>) field.get(obj);
                    int index = list.indexOf(ObjectTypeAdapter.FACTORY);
                    list.set(index, MapTypeAdapter.FACTORY);
                    break;
                }
            }
        } catch (Exception ex) {

        }
        return gson;
    }

    /**
     * JSON转JavaBean
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T json2Bean(String json, Class<T> clazz) {
        return GSON.fromJson(json, clazz);
    }

    /**
     * Json转Map
     *
     * @param json
     * @return
     */
    public static Map json2Map(String json) {
        return json2Bean(json, Map.class);
    }

    /**
     * JavaBean转Map
     *
     * @param object
     * @return
     */
    public static Map object2Map(Object object) {
        String json = object2Json(object);
        return json2Bean(json, Map.class);
    }

    /**
     * Object转String
     *
     * @param object
     * @return
     */
    public static String object2Json(Object object) {
        return GSON.toJson(object);
    }

}
